package com.example.diancai.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.diancai.annotations.IgnoreAuth;
import com.example.diancai.consts.RedisKeyConst;
import com.example.diancai.consts.RequestAttributeKeyConst;
import com.example.diancai.consts.ResponseCode;
import com.example.diancai.dto.CurrentPlayer;
import com.example.diancai.util.AuthUtil;
import com.example.diancai.util.ContextUtil;
import com.example.diancai.util.RedisUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.naming.AuthenticationException;

/**
 * 请求拦截器
 */
public class RequestInterceptor implements HandlerInterceptor {

    private RedisUtil redisUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put("requestId", String.valueOf(System.currentTimeMillis()));
        MDC.put("requestUrl", request.getRequestURI());
        MDC.put("requestMethod", request.getMethod());

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.getMethodAnnotation(IgnoreAuth.class) != null) {
                return true;
            }
            if (handlerMethod.getBeanType().getAnnotation(IgnoreAuth.class) != null) {
                return true;
            }

            // 获取请求头token
            String token = AuthUtil.getToken(request);
            if (StrUtil.isBlank(token)) {
                return true;
                // throw new AuthenticationException(ResponseCode.tokenNotFount.name());
            }
            if (redisUtil == null) redisUtil = ContextUtil.getBean(RedisUtil.class);
            CurrentPlayer activeUser = (CurrentPlayer) redisUtil.getObj(RedisKeyConst.AUTH + token, CurrentPlayer.class);
            if (ObjectUtil.isNull(activeUser)) {
                throw new AuthenticationException(ResponseCode.tokenInvalidation.name());
            }
            request.setAttribute(RequestAttributeKeyConst.USERINFO, activeUser);
            return true;
        }
        return true;
    }


}
